package com.yyk.yiliao.ui.trade;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.CountDownTimer;
import com.google.android.material.textfield.TextInputEditText;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.bean.Sendsms_Info;
import com.yyk.yiliao.util.BtnToEditListenerUtil;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.util.rx.RxUtils;

import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 设置交易密码    --填写手机号
 */
public class InvestPasswordActivity extends BaseActivity {
    public static InvestPasswordActivity intance;

    @BindView(R.id.et_phone) //手机号
            TextInputEditText etPhone;
    @BindView(R.id.et_sms)//验证码
            TextInputEditText etSms;
    @BindView(R.id.ll_sendsms)//点击获取验证码
            LinearLayout llSendsms;
    @BindView(R.id.tv_sendsms)//获取验证码
            TextView tvSendsms;
    @BindView(R.id.bt_next)//下一步
            Button btNext;

    private int cadeSms;//手机验证码
    private String photoFlag; //手机号
    private String phone;


    @Override
    public int getLayoutId() {
        return R.layout.activity_invest_password;
    }

    @Override
    public void initView() {
        initToolbar();
        initButton();
        phone = Hawk.get("phone") + "";
        String maskNumber = phone.substring(0, 3) + "****" + phone.substring(7, phone.length());
        etPhone.setText(maskNumber);
    }

    private void initButton() {
        BtnToEditListenerUtil.getInstance().setBtn(btNext).setBackgroud(R.color.blue_51, R.color.blue_89)
                .addEditView(etPhone)
                .addEditView(etSms)
                .build();
        etPhone.addTextChangedListener(new TextWatcher() {
            //当长度=11的时候，判断是注册  提示去登陆。
            int length;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @SuppressLint("ResourceAsColor")
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                length = s.length();
//                photoFlag = String.valueOf(s);
//                if (length == 11) {
//                    //在这里做了一个判断，如果手机号满11位但是不符合手机号格式，会自动提示手机号码格式不正确
//                    boolean validPhoneNumber = ValidUtils.getInstance().isValidPhoneNumber(photoFlag);
//                    if (!validPhoneNumber) {
//                        ToastUtil.showShort(mActivity, "手机号码格式不正确");
//                        tvSendsms.setTextColor(getResources().getColor(R.color.gray_c1));
//                        tvSendsms.setEnabled(false);
//                    } else {
//                        tvSendsms.setTextColor(getResources().getColor(R.color.gray_c1));
//                        tvSendsms.setEnabled(true);
//                    }
//                } else {
//                    tvSendsms.setTextColor(getResources().getColor(R.color.gray_c1));
//                    tvSendsms.setEnabled(false);
//                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

    }

    private void initToolbar() {
        setBackArrow();
        setTitle("设置交易密码");
    }

    @Override
    public void initData() {
        intance = this;
    }

    /**
     * 发送验证码
     */
    private TimeCount timeCount;


    /**
     * 设置 60秒时间 倒计时
     */
    private class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
//            mLoginEdit.setBackgroundColor(Color.parseColor("#B6B6D8"));
            llSendsms.setClickable(false);
            tvSendsms.setText(millisUntilFinished / 1000 + "s后重发");
            tvSendsms.setTextColor(getResources().getColor(R.color.gray_c1));

        }

        @Override
        public void onFinish() {
            llSendsms.setClickable(true);
            tvSendsms.setText("获取验证码");
            tvSendsms.setTextColor(getResources().getColor(R.color.blue_51));

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timeCount != null) {
            timeCount.cancel();
        }
    }

    @OnClick({R.id.tv_sendsms, R.id.bt_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_sendsms:
                sendSms();
                break;
            case R.id.bt_next:
                sendNext();
                break;
        }
    }

    private void sendSms() {

        Map<String, String> map = new TreeMap<>();
        map.put("telphone", phone);
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postSendsms(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<Sendsms_Info>() {


                    @Override
                    public void onNext(Sendsms_Info info) {
                        Logger.e("发送验证码" + info.toString());
                        if (info.getCode() == 0) {
                            ToastUtil.showShort(mActivity, "短信获取次数过多");
                            return;
                        } else {
                            if (info.getCode() == 1) {
                                //获取到的验证码
                                cadeSms = info.getData();
                                Logger.i("手机验证码" + cadeSms + "");
                            }
                        }
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                });
        timeCount = new TimeCount(60000, 1000);
        timeCount.start();
    }

    private void sendNext() {
        String sms = etSms.getText().toString().trim();
//        if (phone.length() != 11) {
//            ToastUtil.showShort(mActivity, "手机号格式不正确");
//            return;
//        }
        if (sms.length() != 4) {
            ToastUtil.showShort(mActivity, "验证码格式不正确");
            return;
        }
        if (sms.equals(cadeSms + "")) {
            Bundle bundle = new Bundle();
            bundle.putString("tel", phone);
            bundle.putString("code", sms);
            startAct(InvestPassword2Activity.class, bundle);
        } else {
            ToastUtil.showShort(mActivity, "验证码输入不正确");
            return;
        }
    }

}
